<?php
// +-----------------------------------------------------------------------------------------------
// | 简易CMS
// +-----------------------------------------------------------------------------------------------
// | [请手动修改文件描述]
// +-----------------------------------------------------------------------------------------------
// | Author: IT果农 <htmambo@163.com> <http://www.haolie.net>
// +-----------------------------------------------------------------------------------------------
// | Version $Id: CategoriesController.class.php 26 2016-10-16 07:57:05Z IT果农 <htmambo@163.com> $
// +-----------------------------------------------------------------------------------------------
namespace app\admin\controller;

class Categories extends AdminController {
    public $cateListAll = array();

    public function _initialize() {
        $this->assign('list', model('Categories')->lists());
        parent::_initialize();
    }

    public function index() {
        $m = model('Categories')->lists();
        $tree = new \CMS\Tree($m, 'catid', 'upid');
        $list = $tree->buildTree();
        $this->assign('list', $list);
        $tpl = getTpl('view');
        $this->assign('contenttpls', $tpl);
        $tpl = getTpl('list');
        $this->assign('listtpls', $tpl);
        
        // cache('catetype',null);
        return $this->fetch();
    }

    public function remove() {
        $catid = input('get.catid', 0, 'intval');
        if (!$catid) {
            return $this->error('对不起，你没有指定要删除的分类！');
        }
        $model = model('Categories');
        // 有子分类不能删除
        $map = array(
            'upid' => $catid 
        );
        $count = $model->where($map)->count();
        if ($count) {
            return $this->error('对不起，指定的分类下还有子分类未被删除！');
        }
        // 有文章不能删除
        $map = array(
            'catid' => $catid 
        );
        $count = db('ArticleTitle')->where($map)->count();
        if ($count) {
            return $this->error('对不起，指定的分类下还有文章没有删除！');
        }
        $result = $model->destroy($catid);
        return $this->success('删除成功！');
    }

    /**
     * 保存分类信息
     */
    public function update() {
        $data = input('post.');
        $model = model('Categories');
        $msg = '分类《'.$data['catname'].'》';
        if ($data['catid']) {
            $msg .= '更新';
            $result = $model->isUpdate(true)->save($data);
        } else {
            $msg .= '添加';
            $result = $model->save($data);
        }
        if ($result) {
            return $this->success($msg.'成功！');
        } else {
            return $this->error($msg.'失败！<br />'.$model->getError());
        }
    }
}
